//
//  AppDelegate.swift
//  Weibo T
//
//  Created by mac on 15/11/26.
//  Copyright © 2015年 陈肖坤. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        let account = UserAccount.loadAccount()
        print(account)
        
        setThemeColor()
        
        //检查是否是新版本
//        let isnew = isNewVersion()
        //注册通知
        registerNotification()
        
        //手动实例化Window
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.makeKeyAndVisible()
        
        //MainViewController()  NewFeatureCollectionViewController()
        window?.rootViewController = defaultRootViewController()
        return true
    }
    private func defaultRootViewController() -> UIViewController{
        //判断用户是否登录
        if UserAccountViewModel().userLogin {
            //是否是新版本
            if isNewVersion() {
                return NewFeatureCollectionViewController()
            }
            
            return WelcomeViewController()
        }
        
        //如果没有登录
        return MainViewController()
    }
    
    @objc private func switchRootVC(n: NSNotification) {
        print(n)
        
        window?.rootViewController = n.object == nil ? MainViewController() : WelcomeViewController()
    }
    
    private func registerNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootVC:", name: WBSwitchRootVCNotification, object: nil)
    }
    
    //设置全局Color
    private func setThemeColor() {
       UITabBar.appearance().tintColor = themeColor
       UINavigationBar.appearance().tintColor = themeColor

    
    }
    //MARK: 判断是否是新版本
    private func isNewVersion() -> Bool {
        //1.获取引用当前版本
        let dict = NSBundle.mainBundle().infoDictionary!
        let currentNum = (dict["CFBundleShortVersionString"] as! NSString).doubleValue
        //2. 获取上一个版本
        //设置 key
        let sandBoxKey = "sandBoxKey"
        let defaults = NSUserDefaults.standardUserDefaults()
        let lastVersion = defaults.doubleForKey(sandBoxKey)
        //记录当前的系统版本
        defaults.setDouble(currentNum, forKey: sandBoxKey)
        //同步沙盒
        defaults.synchronize()
        //3.比较两个版本
        return currentNum > lastVersion
    }
    //析构方法中移除通知
    // 本质上不用移除   编码习惯而已
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

}

